﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepositoryAndEf.Core;
using RepositoryAndEf.Core.Data;
using System.Linq.Expressions;

namespace RepositoryAndEf.Data
{
    public class MockRepository<T> : IRepository<T> where T : BaseEntity
    {
        private List<T> _list = new List<T>();

        public T GetById(Guid id)
        {
            return _list.FirstOrDefault(e => e.Id == id);
        }

        public IEnumerable<T> Get(Expression<Func<T, bool>> predicate)
        {
            return _list.Where(predicate.Compile());
        }

        public bool Insert(T entity)
        {
            if (GetById(entity.Id) != null)
            {
                throw new InvalidCastException("The id has already existed");
            }

            _list.Add(entity);
            return true;
        }

        public bool Update(T entity)
        {
            var existingEntity = GetById(entity.Id);
            if (existingEntity == null)
            {
                throw new InvalidCastException("Cannot find the entity.");
            }

            existingEntity = entity;
            return true;
        }

        public bool Delete(T entity)
        {
            var existingEntity = GetById(entity.Id);
            if (existingEntity == null)
            {
                throw new InvalidCastException("Cannot find the entity.");
            }

            _list.Remove(entity);
            return true;
        }
    }
}
